<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wms_ctl_admin_orderform extends desktop_controller{

    var $workground = 'wms_ctl_admin_orderform';
    var $pagelimit = 10;
    var $stocknotice_model ;
    public function __construct($app)
    {
        parent::__construct($app);
        $this->member_model = $this->app->model('orderform');
        header("cache-control: no-store, no-cache, must-revalidate");
    }
    //备货通知单首页
   function index()
   {

        $filter=array();
       // $is_super = $this->user->is_super();
       // if($is_super != 1){
       //     $filter['operator'] = $this->user->get_name();
       // }

        $params = array(
            'title' => '备货通知单',
            'actions' => array(
                'new' => array(
                    'label' => '新建',
                    'href' => 'index.php?app=wms&ctl=admin_orderform&act=add_orderform',
                        'target' => '_blank',
                ),
                'confirm' => array(
                    'label' => '确认',
                    'submit' => 'index.php?app=wms&ctl=admin_orderform&act=doConfirm',
                ),
                'undoconfirm' => array(
                    'label' => '取消确认',
                    'submit' => 'index.php?app=wms&ctl=admin_orderform&act=doundoConfirm',
                ),
                'print' => array(
                    'label' => '打印',
                    'submit' => 'index.php?app=wms&ctl=admin_orderform&act=doPrint',
                        'target' => '_blank',
                ),
                'delete' => array(
                    'label' => '删除',
                    'submit' => 'index.php?app=wms&ctl=admin_orderform&act=doDelete',
                ),
            ),
            'base_filter' => $filter,
            //'base_filter' => '',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag' => false,
            'use_buildin_recycle' => false,
            'use_buildin_export' => true ,
            'use_buildin_import' => false,
            'use_buildin_filter' => true,
            'allow_detail_popup' => true,
            'max_actions' => 8,
            'use_view_tab' => false,

            'orderBy' => 'create_time desc',
        );
        $this->finder('wms_mdl_orderform', $params);

    }
    //添加备货
    function add_orderform()
    {


        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['operator'] = $operator;
        $this->pagedata['cur_date']=$this->autocreatebn();
        //$this->pagedata['cur_date'] = date('YmdHis',time()).rand(1000,9999);
        //$this->singlepage("admin/purchase/purchase_add.html");
        $this->singlepage('admin/orderform/orderform_add.html');
    }
    function autocreatebn()
    {
        $bn='';
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $time_begin= mktime(0,0,0,$m,$d,$y);
        $time_end= mktime(23,59,59,$m,$d,$y);
        $delivery_model = $this->app->model('orderform');
        $filter['create_time|between'] = array($time_begin, $time_end);
        $delivery= $delivery_model->getList('orderform_bn',$filter,0,1,'create_time desc');
        if($delivery[0]['orderform_bn']=='')
        {
            $bn ='BF'.date('Ymd',time()).'01';
        }
        else
        {
            $bn=substr($delivery[0]['orderform_bn'] , 10 , 2);
            $num=intval($bn)+1;
            if($num<=9)
            {
                $bn ='BF'.date('Ymd',time()).'0'.$num;
            }else
            {
                $bn ='BF'.date('Ymd',time()).$num;
            }
        }
        return $bn;
    }

    /**
     * 基础物料列表弹窗数据获取方法
     *
     * @param Void
     * @return String
     */
    function finddelivery($supplier_id=null)
    {

        $base_filter['print_status'] = '0';
        $base_filter['status'] = '0';
        $base_filter['is_ship'] = 'false';
        $base_filter['deliverytype'] = array('pickup','delivery','auto','batch','single');
        $base_filter['is_form'] = 'false';
        if(!$_POST['shop_id']){
            $base_filter['shop_id'] = $this->shopIds;
        }else{
            $base_filter['shop_id'] = $_POST['shop_id'];
        }

        $params = array(
                'title'=>'发货单',
                'use_buildin_new_dialog' => false,
                'use_buildin_set_tag'=>false,
                'use_buildin_recycle'=>false,
                'use_buildin_export'=>false,
                'use_buildin_import'=>false,
                'use_buildin_filter'=>true,
                'base_filter' => $base_filter,
        );
        $this->finder('wms_mdl_delivery', $params);
    }

    function getdeliverys()
    {
        //$basicMaterialSelect    = kernel::single('delivery_select');#基础物料 ExBOY
        //$basicMaterialBarcode    = kernel::single('material_basic_material_barcode');#条形码 ExBOY
        $omeMdl = app::get('ome')->model('orders');
        $omeExtOrdLib = kernel::single('ome_extint_order');
        $pro_id = $_POST['product_id'];
        if(!$_POST['shop_id']){
            $shopId = $this->shopIds;
        }else{
            $shopId = $_POST['shop_id'];
        }
        if (is_array($pro_id)){
            $filter['delivery_id'] = $pro_id;
        }
         if (isset($_POST['filter']['advance']) && $_POST['filter']['advance'])
        {
            $arr_filters    = explode(',', $_POST['filter']['advance']);
            foreach ($arr_filters as $obj_filter)
            {
                $arr    = explode('=', $obj_filter);
                $filter[$arr[0]]    = $arr[1];
            }
            if($filter['_create_time_search'] == 'than' || $filter['_create_time_search'] == 'lthan')
            {
                $filter['_DTYPE_TIME'][0] = $filter['_DTYPE_TIME[]'];
                $filter['_DTIME_']['H']['create_time'] = $filter['_DTIME_[H][create_time]'];
                $filter['_DTIME_']['M']['create_time'] = $filter['_DTIME_[M][create_time]'];
            }
            if($filter['_create_time_search'] == 'between')
            {
                $filter['_DTYPE_TIME'][0] = $filter['_DTYPE_TIME[]'];
                $filter['_DTIME_']['H']['create_time_from'] = $filter['_DTIME_[H][create_time_from]'];
                $filter['_DTIME_']['M']['create_time_from'] = $filter['_DTIME_[M][create_time_from]'];
                $filter['_DTIME_']['H']['create_time_to'] = $filter['_DTIME_[H][create_time_to]'];
                $filter['_DTIME_']['M']['create_time_to'] = $filter['_DTIME_[M][create_time_to]'];
            }
        }
        $filter['print_status'] = '0';
        $filter['status'] = '0';
        $filter['is_ship'] = 'false';
        $filter['is_form'] = 'false';
        $filter['deliverytype'] = array('pickup','delivery','auto','batch','single');

        $delivery_model = $this->app->model('delivery');
        $delivery= $delivery_model->getList('delivery_bn,delivery_id,shop_id,outer_delivery_bn',$filter);

        if (!empty($delivery))
        {
            foreach ($delivery as $k => $item)
            {

                $order_bn = $omeExtOrdLib->getOrderBns($item['outer_delivery_bn']);
                $pause= $omeMdl->getList('pause',array('order_bn' => $order_bn));
                if ($pause[0]['pause'] == 'false') {
                    if($shopId){
                        if(in_array($item['shop_id'],$shopId)){
                            $item['product_id']=$item['delivery_id'];
                            $item['delivery_bn']=$item['delivery_bn'];
                            $rows[]= $item;
                        }
                    }else{
                        $item['product_id']=$item['delivery_id'];
                            $item['delivery_bn']=$item['delivery_bn'];
                            $rows[]= $item;
                    }
                }

            }
        }
        echo "window.autocompleter_json=".json_encode($rows);
    }
    //保存备货通知单
    function doSave()
    {
        $this->begin();
        $orderform_model = $this->app->model('orderform');
        $orderformDeil_model = $this->app->model('orderform_delis');
        $stockappDeil_model = $this->app->model('stockapp_delis');

        $orders_obj = $this->app->model('delivery');
        $delivery_ID = $_POST['delivery_ID'];
        $name = $_POST['purchase_name'];
        $memo = $_POST['memo'];
        $operator = $_POST['operator'];

        $orderform_id = $orderform_model ->getList('id',array('orderform_bn'=>$_POST['purchase_name']));
        if ($orderform_id) 
        {
            $this->end(false, '存在多人同时操作，请稍后重试');
        }

        $arr_order='';
        $arr_order['orderform']['orderform_bn']=$this->autocreatebn();//$_POST['purchase_name'];
        $arr_order['orderform']['remark']=$_POST['memo'];
        $arr_order['orderform']['operator']=$_POST['operator'];
        $arr_order['orderform']['create_time']=time();

        //创建OMS备货通知单
        foreach ($delivery_ID as $k => $v) {
        	$orderform_id = $orderformDeil_model ->getList('id,delivery_bn',array('delivery_id'=>$v));
        	if ($orderform_id) {
        		$this->end(false, $orderform_id[0]['delivery_bn'].'已生成备货通知单');
        	}

            $stockapp_id = $stockappDeil_model ->getList('id,delivery_bn',array('delivery_id'=>$v));
            if ($stockapp_id) {
                $this->end(false, $stockapp_id[0]['delivery_bn'].'已生成备货申请单');
            }
            //add by ldward 2018-09-14 订单发货数量超出，需备货申请时校验
            $rows=$orderform_model->validateQty($v);
            if(!empty($rows))
            {              
                $orders = $orders_obj->getList('delivery_bn,delivery_id,shop_id', array('delivery_id'=>$v,'deliverytype'=> array('pickup','delivery','auto','batch','single')), 0, 1); 
                $this->end(false, '订单号：'.$rows[0]['order_bn'].'发货单号：'.$orders[0]['delivery_bn'].'发货数量异常，请联系管理员！');
            }



        }
        //同个发货单有多个物料，不允许备货、申请
        $res = $orderform_model->insert($arr_order['orderform']);
        foreach ($delivery_ID as $key => $value)
        {
            $deliveryBillLib = kernel::single('wms_delivery_bill');
            $logino = $deliveryBillLib->getPrimaryLogiNoById($value);

            $orders = $orders_obj->getList('delivery_bn,delivery_id,shop_id', array('delivery_id'=>$value,'deliverytype'=> array('pickup','delivery','auto','batch','single')), 0, 1);

            $arr_line='';
            $arr_line['orderform']['delivery_bn']=$orders[0]['delivery_bn'];
            $arr_line['orderform']['shop_id']=$orders[0]['shop_id'];
            $arr_line['orderform']['delivery_id']=$value;
            $arr_line['orderform']['orderform_id']=$res;
            $arr_line['orderform']['logi_no']=$logino;
            $orderform_delis_model = $this->app->model('orderform_delis');
            $orderform_delis_model->insert($arr_line['orderform']);


            $orders_obj->db->exec("update sdb_wms_delivery set is_form = 'true',deliverynote_time='".time()."' where  delivery_id in(".$value.")");
        }
        $this->end(true, '已完成');
    }
    //确认动作
    function doConfirm()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_orderform&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $orderform_model = $this->app->model('orderform');
        $orderform_delis_model = $this->app->model('orderform_delis');
        $orders_obj = $this->app->model('delivery');

        if ($order_info['isSelectedAll']=='_ALL_') {
            $orders = $orderform_model->getList('*', array(), 0, -1);
            foreach ($orders as $key_o => $order) 
            {
                $value = $order['id']; 
                kernel::database()->exec("update sdb_wms_orderform set status = 'confirmed',last_modify='".time()."' where  id in(".$value.");") ;
                kernel::database()->exec("update sdb_wms_delivery set is_ship = 'true',deliverynote_time='".time()."'
                                         where delivery_id in(select delivery_id from sdb_wms_orderform_delis where orderform_id in('".$value."'));");
            }

        }else{
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {
                kernel::database()->exec("update sdb_wms_orderform set status = 'confirmed',last_modify='".time()."' where  id in(".$value.");");
                kernel::database()->exec("update sdb_wms_delivery set is_ship = 'true',deliverynote_time='".time()."'
                                         where delivery_id in(select delivery_id from sdb_wms_orderform_delis where orderform_id in('".$value."'));");
            }
        }      //
        $this->end(true, '已完成');
    }
    function doPrint()
    {
        $operator = kernel::single('desktop_user')->get_name();
        $this->pagedata['operator'] = $operator;
        $this->pagedata['cur_date'] = date('YmdHis',time()).rand(1000,9999);
        $this->_request    = kernel::single('base_component_request');
        $print_post        = $this->_request->get_post();

        $orders_obj = $this->app->model('orderform');
        $data = $orders_obj->getPrintInfo($print_post['id']);
        $this->pagedata['data'] = $data;
//        print_r($data);
        $this->singlepage('admin/orderform/orderform_print.html');
    }
    //确认动作
    function doundoConfirm()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_orderform&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $orderform_model = $this->app->model('orderform');
        $orderform_delis_model = $this->app->model('orderform_delis');
        $orders_obj = $this->app->model('delivery');
        $deliverynote_line_model = $this->app->model('deliverynote_line');

        if ($order_info['isSelectedAll']=='_ALL_') {
            $orders = $orderform_model->getList('*', array(), 0, -1);
            foreach ($orders as $key_o => $order) {
                $value = $order['id'];
                if($order['status']=='confirmed')
                {
                    $orderform_model->db->exec("update sdb_wms_orderform set status = 'unconfirmed',last_modify='".time()."' where  id in(".$value.")");
                    $orderform_delis = $orderform_delis_model->getList('*', array('orderform_id'=>$value));
                    foreach ($orderform_delis as $key => $delivery_id)
                    {
                        $orders_obj->db->exec("update sdb_wms_delivery set is_ship = 'false',deliverynote_time='".time()."' where  delivery_id in(".$delivery_id['delivery_id'].")");
                    }
                }
            }
        }else{
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value)
            {
                $orders = $orderform_model->getList('*', array('id'=>$value), 0, 1);

                if($orders[0]['status']=='confirmed')
                {
                    $orderform_model->db->exec("update sdb_wms_orderform set status = 'unconfirmed',last_modify='".time()."' where  id in(".$value.")");

                    $orderform_delis = $orderform_delis_model->getList('*', array('orderform_id'=>$value));
                    foreach ($orderform_delis as $key => $delivery_id)
                    {
                        $orders_obj->db->exec("update sdb_wms_delivery set is_ship = 'false',deliverynote_time='".time()."' where  delivery_id in(".$delivery_id['delivery_id'].")");
                    }
                }
            }
        }
        $this->end(true, '已完成');
    }
    //确认动作
    function doDelete()
    {
        $max_input_vars = ini_get('max_input_vars');
        ini_set('memory_limit','512M');
        set_time_limit(600);
        $this->begin("index.php?app=wms&ctl=admin_orderform&act=index");
        $this->_request    = kernel::single('base_component_request');
        $order_info        = $this->_request->get_post();

        $orderform_delis_model = $this->app->model('orderform_delis');
        $orderform_model = $this->app->model('orderform');
        $orders_obj = $this->app->model('delivery');

        if ($order_info['isSelectedAll']=='_ALL_') {
            $orders = $orderform_model->getList('*', array(), 0, -1);
            foreach ($orders as $key => $order) {
                $value = $order['id'];
                if ($order['status'] == 'unconfirmed') {
                    $orderform_delis = $orderform_delis_model->getList('*', array('orderform_id' => $value));
                    foreach ($orderform_delis as $key => $delivery_id) {
                        $orders_obj->db->exec("update sdb_wms_delivery set is_form = 'false',deliverynote_time='".time()."' where  delivery_id in(" . $delivery_id['delivery_id'] . ")");
                    }

                    $orderform_model->db->exec("delete from sdb_wms_orderform_delis  where  orderform_id in(" . $value . ");");
                    $orderform_model->db->exec("delete from sdb_wms_orderform  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '备货单号【' . $order['orderform_bn'] . '】状态已确认，删除失败！');
                }
            }
        } else {
            $input = file_get_contents("php://input");
            $input_array = explode('&', $input);
            $number = count($input_array);
            if ($number > $max_input_vars) {
                $msg =  "多选不能超过系统表单最大提交数【".$max_input_vars."】条";
                $this->end(false, $msg);
            }
            foreach ($order_info['id'] as $key_o => $value) {
                $orders = $orderform_model->getList('*', array('id' => $value), 0, 1);

                if ($orders[0]['status'] == 'unconfirmed') {
                    $orderform_delis = $orderform_delis_model->getList('*', array('orderform_id' => $value));
                    foreach ($orderform_delis as $key => $delivery_id) {
                        $orders_obj->db->exec("update sdb_wms_delivery set is_form = 'false',deliverynote_time='".time()."' where  delivery_id in(" . $delivery_id['delivery_id'] . ")");
                    }

                    $orderform_model->db->exec("delete from sdb_wms_orderform_delis  where  orderform_id in(" . $value . ");");
                    $orderform_model->db->exec("delete from sdb_wms_orderform  where  id in(" . $value . ");");
                } else {
                    $this->end(false, '备货单号【' . $orders[0]['orderform_bn'] . '】状态已确认，删除失败！');
                }
            }
        }
        $this->end(true, '已完成');
    }
    function getEditdelivery()
    {

    }
    /**
     * 编辑采购单
     *
     */
    function editOrderform(){
        $this->begin('index.php?app=wms&ctl=admin_orderform&act=index');

        $id = $_GET['id'];

        $poObj = app::get('purchase')->model('po');
        $suObj = app::get('purchase')->model('supplier');
        $brObj = app::get('ome')->model('branch');

        $data = $poObj->dump($po_id, '*', array('po_items' => array('*')));

        //当前供应商
        $supplier_detail = $suObj->dump($data['supplier_id'], 'supplier_id,name');
        $this->pagedata['supplier_detail'] = $supplier_detail;

        if (!$branch_mode){
            $branch_mode = 'single';
        }
        $this->pagedata['branch_mode'] = $branch_mode;

        $su = $suObj->dump($data['supplier_id'],'name');
        $br = $brObj->dump($data['branch_id'], 'name');
        $data['branch_name'] = $br['name'];
        $data['supplier_name'] = $su['name'];
        //到货天数
        $diff_time = $data['arrive_time'] - $data['purchase_time'];
        $data['diff_days'] = floor($diff_time/(24*60*60));
        $this->pagedata['po_items'] = $data['po_items'];
        $data['memo'] = unserialize($data['memo']);
        $this->pagedata['po'] = $data;
        //$this->singlepage("admin/purchase/purchase_edit.html");
        $this->singlepage("admin/orderform/orderform_edit.html");
    }
}
